package com.iams.manage.service.impl;

import java.util.List;
import com.iams.common.utils.DateUtils;
import com.iams.common.utils.uuid.UUID;
import com.iams.manage.domain.BorrowApproval;
import com.iams.manage.service.IBorrowApprovalService;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import com.iams.manage.mapper.BorrowRecordMapper;
import com.iams.manage.domain.BorrowRecord;
import com.iams.manage.service.IBorrowRecordService;
import org.springframework.transaction.annotation.Transactional;

import com.iams.manage.validator.BorrowRecordValidator;

/**
 * 借阅记录Service业务层处理
 * 
 * @author 张金明
 * @date 2025-01-15
 */
@Service
public class BorrowRecordServiceImpl implements IBorrowRecordService 
{
    @Autowired
    private BorrowRecordMapper borrowRecordMapper;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private IBorrowApprovalService borrowApprovalService;

    @Autowired
    private BorrowRecordValidator borrowRecordValidator;


    /**
     * 查询借阅记录
     * 
     * @param id 借阅记录主键
     * @return 借阅记录
     */
    @Override
    public BorrowRecord selectBorrowRecordById(Long id)
    {
        return borrowRecordMapper.selectBorrowRecordById(id);
    }

    /**
     * 查询借阅记录列表
     * 
     * @param borrowRecord 借阅记录
     * @return 借阅记录
     */
    @Override
    public List<BorrowRecord> selectBorrowRecordList(BorrowRecord borrowRecord)
    {
        return borrowRecordMapper.selectBorrowRecordList(borrowRecord);
    }

    /**
     * 新增借阅记录
     * 
     * @param borrowRecord 借阅记录
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBorrowRecord(BorrowRecord borrowRecord)
    {
        borrowRecord.setCreateTime(DateUtils.getNowDate());
        borrowRecord.setApplyTime(DateUtils.getNowDate());
        borrowRecord.setStatus("pending"); // 设置初始状态为待审批


        // 借阅数据验证
        borrowRecordValidator.validate(borrowRecord);
        if(borrowRecord.getProcessName() == null)
        {
            borrowRecord.setProcessName("BorrowApproval");
        }

        // 先保存借阅记录
        int rows = borrowRecordMapper.insertBorrowRecord(borrowRecord);

        if (rows > 0) {
            // 生成业务键
            String businessKey = UUID.randomUUID().toString();

            try {
                // 启动流程实例
                ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey(borrowRecord.getProcessName())
                        .withBusinessKey(businessKey)
                        .withName(borrowRecord.getUserName() + "档案借阅申请")
                        .build());

                // 创建审批记录
                BorrowApproval borrowApproval = new BorrowApproval();
                borrowApproval.setApplyId(borrowRecord.getId());
                borrowApproval.setInstanceId(processInstance.getId());
                borrowApproval.setBusinessKey(businessKey);
                borrowApproval.setCreateTime(DateUtils.getNowDate());

                // 保存审批记录
                borrowApprovalService.insertBorrowApproval(borrowApproval);

            } catch (AccessDeniedException e) {
                throw new RuntimeException("启动工作流程失败", e);
            }
        }

        return rows;
    }

    /**
     * 修改借阅记录
     * 
     * @param borrowRecord 借阅记录
     * @return 结果
     */
    @Override
    public int updateBorrowRecord(BorrowRecord borrowRecord)
    {
        borrowRecord.setUpdateTime(DateUtils.getNowDate());
        return borrowRecordMapper.updateBorrowRecord(borrowRecord);
    }

    /**
     * 批量删除借阅记录
     * 
     * @param ids 需要删除的借阅记录主键
     * @return 结果
     */
    @Override
    public int deleteBorrowRecordByIds(Long[] ids)
    {
        return borrowRecordMapper.deleteBorrowRecordByIds(ids);
    }

    /**
     * 删除借阅记录信息
     * 
     * @param id 借阅记录主键
     * @return 结果
     */
    @Override
    public int deleteBorrowRecordById(Long id)
    {
        return borrowRecordMapper.deleteBorrowRecordById(id);
    }


    /**
     * 根据（用户ID与档案ID）查找信息
     *
     * @param archiveId userId 借阅记录主键 用户ID
     * @return 结果
     */
    @Override
    public List<BorrowRecord> selectBorrowRecordByArchiveIDandUserID(Long archiveId, Long userId)
    {
        return borrowRecordMapper.selectBorrowRecordList(new BorrowRecord(archiveId, userId));
    }


    // 每天0点检查并更新借阅状态
    // 借阅时间以天计算，因此按天更新借阅状态
    @Override
    @Scheduled(cron = "0 0 0 * * ?")
    public void borrowRecordStatus()
    {
        BorrowRecord borrowRecord = new BorrowRecord();
        borrowRecord.setStatus("approved");

        borrowRecordMapper.selectBorrowRecordList(borrowRecord).forEach(record -> {
            if ((record.getEndDate().getTime() < System.currentTimeMillis()))
            {
                record.setStatus("overdue");
            }
            borrowRecordMapper.updateBorrowRecord(record);
        });

    }

}
